﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
//using HK.Reports;

namespace grid
{
    enum fh { s10n, s18n, Snds10n, Snds18n, s10o, s18o, Snds10o, Snds18o }
    enum g_style : int
    {
        col = 1,
        width = 2,
        captions = 3,
        font = 4,
        fontSize = 5,
        fontStyle = 6,
        typeCol = 7,
        SQLquery = 8,
        periodS = 9,
        periodPo = 10,
        name_col = 11,
        SQL_1 = 12,
        SQL_2 = 13,
        SQL_3 = 14,
        SQL_4 = 15,
        SQL_5 = 16,
        SQL_6 = 17,
        SQL_7 = 18,
        SQL_8 = 19,
        SQL_9 = 20,
        SQL_10 = 21,
        FIND_1 = 22,
        FIND_2 = 23,
        FIND_3 = 24,
        FIND_4 = 25,
        FIND_5 = 26,
        FIND_6 = 27,
        FIND_7 = 28,
        FIND_8 = 29,
        FIND_9 = 30,
        FIND_10 = 31,
        headReport = 32,
        serv = 33

    }
    enum FAED { edit_col, edit_cell, edit_row}

    public partial class FormGRIDm : Form
    {
        #region declaration
        functionService.prm_grid PLPg = new functionService.prm_grid("PLP_grid");
        functionService.connDB cnDB = new functionService.connDB();
        FontStyle fStyle;
        #endregion

        public FormGRIDm()
        {
            InitializeComponent();
        }
        public FormGRIDm(DataTable dt)
            : this()
        {
            string ser = PLPg.tk((int)g_style.serv);
            toolStripComboBox2.Text = ser;
            cnDB.setConn(ser,"zarpl");
            try
            {
                cnDB.co();
            }
            catch
            {
                cnDB.setConn("localhost","zarpl");
                cnDB.co();
                PLPg.put((int)g_style.serv,"localHost");
            }
            DataTable dt1 = cnDB.selectAny(PLPg.tk((int)g_style.SQL_1));
            cnDB.cc();
            dataGridView1.DataSource = dt1;
            setTSMI("");
            getCount();
            setFormGrid();
            setComplete();
            setCurServ();
        }
        public FormGRIDm(DataView dv)
            : this()
        {
            dataGridView1.DataSource = dv;
        }

        #region events
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            saveDataXML();
            MessageBox.Show("Изменения сохранены успешно.");
        } // Сохранить в XML
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            SaveFileDialog SV = new SaveFileDialog();
            SV.Filter = "MSExcel files (*.xls)|*.xls|All files (*.*)|*.*";
            SV.FilterIndex = 1;
            SV.RestoreDirectory = true;
            if (SV.ShowDialog() == DialogResult.OK)
            {
                saveDataXLS(SV.FileName.ToString());
                MessageBox.Show(string.Concat("Экспорт в файл ",SV.FileName.ToString()," успешно завершен."));
            }
        } // Сохранить в XLS
        private void toolStripMenuItem1_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Сохранить параметры формы");
        }
        private void toolStripMenuItem1_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripMenuItem2_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Експорт содержимого в Excel");
        }
        private void toolStripMenuItem2_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            FontDialog fd = new FontDialog();
            fd.Font = new Font(PLPg.tk((int)g_style.font), Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0)), fStyle);
            if (fd.ShowDialog() == DialogResult.OK)
            {
                dataGridView1.Font = new Font(fd.Font.Name, fd.Font.Size, fd.Font.Style);
                PLPg.put((int)g_style.font,fd.Font.Name);
                PLPg.put((int)g_style.fontSize, fd.Font.Size);
                PLPg.put((int)g_style.fontStyle, fd.Font.Style);
            }
        } // Установка параметров шрифта
        private void toolStripMenuItem3_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Параметры шрифта");
        }
        private void toolStripMenuItem3_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            int FSize = Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0));
            FSize = FSize + 2;
            PLPg.put((int)g_style.fontSize, FSize);
            setFontStyle();
            dataGridView1.Font = new Font(PLPg.tk((int)g_style.font), FSize, fStyle);
            dataGridView1.AutoResizeColumns();
        }
        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            int FSize = Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0));
            FSize = FSize - 2;
            PLPg.put((int)g_style.fontSize, FSize);
            setFontStyle();
            dataGridView1.Font = new Font(PLPg.tk((int)g_style.font), FSize, fStyle);
            dataGridView1.AutoResizeColumns();
        }
        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;
        }
        private Form ED;
        private Form qSQL;
        private Form Date;
        private TextBox qSQL_TB;
        private ListBox qSQL_LB;
        private Label LB;
        private void qSQL_LB_Click(object sender, EventArgs e)
        {
            qSQL_TB.Text = qSQL_LB.SelectedItem.ToString();
        }
        private void TB_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string w_array = "";
                string[] colu = PLPg.tk((int)g_style.captions).Split(';');
                int contArray = colu.Count();
                int i = 0;
                colu[dataGridView1.CurrentCellAddress.X] = (sender as TextBox).Text;
                for (i = 0; i < contArray; i++)
                {
                    w_array = w_array + string.Concat(colu[i], ";");
                }
                PLPg.put((int)g_style.captions, w_array);
                setFormGrid();
                ED.Close();
            }
            else if (e.KeyCode == Keys.Escape)
            {
                ED.Close();
            }
        }
        private void qSQL_TB_KeyDown(object sender, KeyEventArgs e)
        {
            string[] sqlQuery = new string[30];
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    for (int i = 12; i <= 21; i++)
                    {
                        sqlQuery[i] = PLPg.tk(i);
                    }
                    cnDB.setConn(PLPg.tk((int)g_style.serv), "zarpl");
                    cnDB.co();
                    string TB_text = (sender as TextBox).Text;
                    DataTable dtq = cnDB.selectAny(TB_text);
                    cnDB.cc();
                    dataGridView1.DataSource = dtq;
                    if (TB_text != PLPg.tk((int)g_style.SQL_1))
                    {
                        for (int i = 12; i <= 20; i++)
                        {
                            PLPg.put(i + 1, sqlQuery[i]);
                        }
                        PLPg.put((int)g_style.SQL_1, TB_text);
                    }
                    updateListBox();
                    saveDataXML();
                    qSQL.Close();
                }
                catch (Exception emes) { MessageBox.Show(emes.Message); }
            }
            else if (e.KeyCode == Keys.Escape)
            {
                qSQL.Close();
            }
            getCount();
        }
        private void qSQL_LB_DoubleClick(object sender, EventArgs e)
        {
            string[] sqlQuery = new string[30];
            try
            {
                for (int i = 12; i <= 21; i++)
                {
                    sqlQuery[i] = PLPg.tk(i);
                }
                cnDB.setConn("serverExp", "zarpl");
                cnDB.co();
                string LB_text = (sender as ListBox).Text;
                DataTable dtq = cnDB.selectAny(LB_text);
                cnDB.cc();
                dataGridView1.DataSource = dtq;
                if (LB_text != PLPg.tk((int)g_style.SQL_1))
                {
                    for (int i = 12; i <= 20; i++)
                    {
                        PLPg.put(i + 1, sqlQuery[i]);
                    }
                    PLPg.put((int)g_style.SQL_1, LB_text);
                }
                updateListBox();
                saveDataXML();
                qSQL.Close();
            }
            catch (Exception emes) { MessageBox.Show(emes.Message); }
            getCount();
        }
        private void dtPik1_DateSelected(object sender, DateRangeEventArgs e)
        {
            PLPg.put((int)g_style.periodS, (sender as MonthCalendar).SelectionStart.ToShortDateString());
        }
        private void dtPik2_DateSelected(object sender, DateRangeEventArgs e)
        {
            PLPg.put((int)g_style.periodPo, (sender as MonthCalendar).SelectionStart.ToShortDateString());
        }
        private void bOk_Click(object sender, EventArgs e)
        {
            string s = PLPg.tk((int)g_style.periodS).Replace('.','/');
            string po = PLPg.tk((int)g_style.periodPo).Replace('.','/');
            string nameCol = PLPg.tk((int)g_style.name_col);
            ((DataTable)this.dataGridView1.DataSource).DefaultView.RowFilter = string.Concat(nameCol, " >= '",s,"' AND ", nameCol, " <= '",po,"'");
            Date.Close();
        }
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {

        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }
        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
        }
        private void toolStripMenuItem7_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Авторазмер столбцов");
        }
        private void toolStripMenuItem7_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripMenuItem4_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Увеличить масштаб");
        }
        private void toolStripMenuItem4_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripMenuItem5_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Уменьшить масштаб");
        }
        private void toolStripMenuItem5_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripMenuItem6_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Режим выделения - по столбцам");
        }
        private void toolStripMenuItem6_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
        private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
        {

        }
        private void toolStripMenuItem6_Click_1(object sender, EventArgs e)
        {
            setMode(FAED.edit_col);
        }
        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            setMode(FAED.edit_row);
        }
        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            setMode(FAED.edit_cell);
        }
        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {

        }
        private void toolStripMenuItem9_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Режим просмотра таблицы");
        }
        private void toolStripMenuItem9_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripMenuItem6_MouseEnter_1(object sender, EventArgs e)
        {
            setTSMI("Режим редактирования наименований колонок");
        }
        private void toolStripMenuItem6_MouseLeave_1(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void dataGridView1_Click(object sender, EventArgs e)
        {
            cellclick();
        }
        private void toolStripMenuItem8_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Режим выделения строк");
        }
        private void toolStripMenuItem8_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
        }
        private void toolStripMenuItem12_Click(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader;
        }
        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }
        private void toolStripMenuItem14_Click(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }
        private void toolStripMenuItem15_Click(object sender, EventArgs e)
        {
            querySQL();
        }
        private void toolStripMenuItem15_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Написать SQL запрос");
        }
        private void toolStripMenuItem15_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string nameCol = ((DataTable)this.dataGridView1.DataSource).Columns[toolStripComboBox1.SelectedIndex].ColumnName;
            PLPg.put((int)g_style.name_col, nameCol);
            if (functionService.tagWork.readTAG(PLPg.tk((int)g_style.typeCol), toolStripComboBox1.SelectedIndex) == "System.DateTime")
            {
                toolStripTextBox1.Enabled = false;
                datePik();
            }
            else
            {
                toolStripTextBox1.Enabled = true;
            }
            getCount();
        }
        private void toolStripTextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            string strFind = toolStripTextBox1.Text;
            string[] find = new string[10];
            int i1 = 0;
            if (strFind != "")
            {
                if (e.KeyCode == Keys.Enter)
                {
                    for (int i = 22; i <= 31; i++)
                    {
                        find[i1] = PLPg.tk(i);
                        i1++;
                    }
                    i1 = 0;
                    for (int i = 22; i <= 30; i++)
                    {
                        PLPg.put(i + 1, find[i1]);
                        i1++;
                    }
                    PLPg.put((int)g_style.FIND_1, strFind);
                    string nameCol = ((DataTable)this.dataGridView1.DataSource).Columns[toolStripComboBox1.SelectedIndex].ColumnName;
                    DataTable datT = (DataTable)dataGridView1.DataSource;
                    switch (functionService.tagWork.readTAG(PLPg.tk((int)g_style.typeCol), toolStripComboBox1.SelectedIndex).ToString())
                    {
                        case "System.UInt16":
                        case "System.UInt32":
                        case "System.UInt64":
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Double":
                            ((DataTable)this.dataGridView1.DataSource).DefaultView.RowFilter = string.Concat(nameCol, " = ", strFind);
                            break;
                        case "System.String":
                            ((DataTable)this.dataGridView1.DataSource).DefaultView.RowFilter = string.Concat(nameCol, " LIKE '%", strFind, "%'");
                            break;
                    }
                    setComplete();
                }
            }
            else
            {
                ((DataTable)this.dataGridView1.DataSource).DefaultView.RowFilter = null;
            }
            getCount();
        }
        private void toolStripMenuItem16_Click(object sender, EventArgs e)
        {
           // printTable();
        }
        private void toolStripMenuItem17_Click(object sender, EventArgs e)
        {
            //chekXML();
        }
        private void toolStripComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            PLPg.put((int)g_style.serv, toolStripComboBox2.Text);
        }
        private void toolStripMenuItem16_MouseEnter(object sender, EventArgs e)
        {
            setTSMI("Печать");
        }
        private void toolStripMenuItem16_MouseLeave(object sender, EventArgs e)
        {
            setTSMI("");
        }
        #endregion

        #region workfun
        /// <summary>
        /// Загрузка параметров таблицы 
        /// - кол-во колонок
        /// - ширины столбцов
        /// - подписи столбцов
        /// - шрифт
        /// - размер шрифта
        /// - стиль шрифта
        /// </summary>
        private void setFormGrid()
        {
            int i = dataGridView1.Columns.Count;
            int colCol = Convert.ToInt32(PLPg.tk((int)g_style.col));
            int i1 = 0;
            toolStripComboBox1.Items.Clear();
            if (colCol == i)
            {
                while (i1 < i)
                {
                    dataGridView1.Columns[i1].HeaderText = functionService.tagWork.readTAG(PLPg.tk((int)g_style.captions), i1);
                    dataGridView1.Columns[i1].Width = Convert.ToInt32(functionService.tagWork.readTAG(PLPg.tk((int)g_style.width), i1));
                    dataGridView1.Columns[i1].SortMode = DataGridViewColumnSortMode.NotSortable;
                    i1++;
                }
                updateListBox();
                setFontStyle();
                dataGridView1.Font = new Font(PLPg.tk((int)g_style.font), Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0)), fStyle);
            }
            else
            {
                while (i1 < i)
                {
                    dataGridView1.Columns[i1].SortMode = DataGridViewColumnSortMode.NotSortable;
                    toolStripComboBox1.Items.Add(dataGridView1.Columns[i1].HeaderText);
                    i1++;
                }
                setFontStyle();
                dataGridView1.Font = new Font(PLPg.tk((int)g_style.font), Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0)), fStyle);
            }
            //chekXML();
        }

        /// <summary>
        /// Сохранение параметров таблицы 
        /// - кол-во колонок
        /// - ширины столбцов
        /// - подписи столбцов
        /// - шрифт
        /// - размер шрифта
        /// - стиль шрифта
        /// </summary>
        private void saveDataXML()
        {
            string w_array = "";
            string c_array = "";
            string c_type = "";
            int i1 = 1;
            int i = dataGridView1.Columns.Count;
            PLPg.put((int)g_style.col, i);
            while (i1 <= i)
            {
                if (i1 != i)
                {
                    w_array = w_array + string.Concat(dataGridView1.Columns[i1 - 1].Width, ";");
                    c_array = c_array + string.Concat(dataGridView1.Columns[i1 - 1].HeaderText, ";");
                    c_type = c_type + string.Concat(dataGridView1.Columns[i1 - 1].ValueType.ToString(), ";");
                }
                else if (i1 == i)
                {
                    w_array = w_array + string.Concat(dataGridView1.Columns[i1 - 1].Width);
                    c_array = c_array + string.Concat(dataGridView1.Columns[i1 - 1].HeaderText);
                    c_type = c_type + string.Concat(dataGridView1.Columns[i1 - 1].ValueType.ToString());
                }
                i1++;
            }
            PLPg.put((int)g_style.width, w_array);
            PLPg.put((int)g_style.captions, c_array);
            PLPg.put((int)g_style.font, dataGridView1.Font.Name.ToString());
            PLPg.put((int)g_style.fontSize, dataGridView1.Font.Size.ToString());
            PLPg.put((int)g_style.fontStyle, dataGridView1.Font.Style.ToString());
            PLPg.put((int)g_style.typeCol, c_type);
            //MessageBox.Show("Изменения сохранены.");


        }

        /// <summary>
        /// Экспорт содержимого таблицы в EXCEL (вместе с заголовками)
        /// filePath - полный путь с именем сохраняемого файла
        /// </summary>
        /// <param name="filePath"></param>
        private void saveDataXLS(string filePath)
        {
            string file_path = filePath;
            int clmns = dataGridView1.Columns.Count;
            Int32 rows = dataGridView1.Rows.Count;
            Int32 i = 0;
            Int32 i1 = 0;
            string clType = "String";
            System.IO.StreamWriter file = new System.IO.StreamWriter(file_path);
            file.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            file.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
            file.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
            file.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
            file.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
            file.WriteLine(" <Styles>");
            file.WriteLine("  <Style ss:ID=\"s21\">");
            file.WriteLine("   <NumberFormat ss:Format=\"Fixed\"/>");
            file.WriteLine("  </Style>");
            file.WriteLine(" </Styles>");
            file.WriteLine(" <Worksheet ss:Name=\"Table1\">");
            file.WriteLine("  <Table>");
            file.WriteLine("   <Row>");
            for (i = 0; i < clmns; i++)
            {
                file.WriteLine(string.Concat("    <Cell><Data ss:Type=\"String\">", functionService.tagWork.readTAG(PLPg.tk((int)g_style.captions), i), "</Data></Cell>"));
            }
            file.WriteLine("   </Row>");
            for (i1 = 0; i1 < rows; i1++)
            {
                file.WriteLine("   <Row>");
                for (i = 0; i < clmns; i++)
                {
                    file.WriteLine(string.Concat("    <Cell><Data ss:Type=\"",clType,"\">", dataGridView1.Rows[i1].Cells[i].Value, "</Data></Cell>"));
                }
                file.WriteLine("   </Row>");
            }
            file.WriteLine("  </Table>");
            file.WriteLine(" </Worksheet>");
            file.WriteLine("</Workbook>");
            file.Close();
        }

        /// <summary>
        /// Устанавливает значение в строке состояния
        /// texto - текст, который необходимо отобразить
        /// </summary>
        /// <param name="texto"></param>
        private void setTSMI(string mess)
        {
            if (mess != "")
            {
                int x = Control.MousePosition.X;
                int y = Control.MousePosition.Y;

                LB = new Label();
                LB.BorderStyle = BorderStyle.FixedSingle;
                LB.AutoSize = true;
                LB.Font = new Font("Arial", 8);
                LB.BackColor = Color.LightYellow;
                LB.ForeColor = Color.Black;
                LB.Text = mess;
                int wi = LB.Size.Width;
                Point p = new Point(x + 12, y + 25);
                LB.Location = this.PointToClient(p);
                this.Controls.Add(LB);
                LB.BringToFront();
            }
            else
            {
                this.Controls.Remove(LB);
            }
        }

        /// <summary>
        /// Обработчик события клика мышкой на ячейке.
        /// В зависимости от режима FAED выбирается нужное действие.
        /// </summary>
        private void cellclick()
        {
                if (dataGridView1.SelectionMode == DataGridViewSelectionMode.FullColumnSelect)
                {
                    //Инициализация формы
                    int ind = dataGridView1.CurrentCellAddress.X;
                    ED = new Form();

                    // Создание ТекстБокса
                    TextBox TB = new TextBox();
                    TB.Text = functionService.tagWork.readTAG(PLPg.tk((int)g_style.captions), ind);
                    TB.Location = new System.Drawing.Point(50, 0);
                    TB.BorderStyle = BorderStyle.FixedSingle;
                    TB.Width = 450;
                    TB.Height = 25;
                    TB.Font = new Font("Arial", 14);
                    TB.Name = "TB";

                    // Создание Лейбла
                    Label LAB = new Label();
                    LAB.TextAlign = ContentAlignment.MiddleCenter;
                    LAB.Width = 51;
                    LAB.Height = 29;
                    LAB.Name = "LAB";
                    LAB.Font = new Font("Arial", 14);
                    LAB.BorderStyle = BorderStyle.FixedSingle;
                    LAB.Text = ind.ToString();

                    ED.Width = 500;
                    ED.Height = 25;
                    ED.Controls.Add(TB);
                    ED.Controls.Add(LAB);
                    ED.StartPosition = FormStartPosition.CenterParent;
                    ED.FormBorderStyle = FormBorderStyle.None;
                    TB.KeyDown += new KeyEventHandler(TB_KeyDown);
                    ED.ShowDialog();
                }
        }

        /// <summary>
        /// Установка режима таблицы (выделение по строкам, столбцам, 
        /// редактирование заголовков)
        /// </summary>
        /// <param name="m"></param>
        private void setMode(FAED m)
        {
            int col = dataGridView1.Columns.Count;
            if (m == FAED.edit_cell)
            {
                dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
                for (int i = 0; i < col; i++)
                {
                    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
            }
            else if (m == FAED.edit_col)
            {
                for (int i = 0; i < col; i++)
                {
                    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;
            }
            else if (m == FAED.edit_row)
            {
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                for (int i = 0; i < col; i++)
                {
                    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
            }
        }

        /// <summary>
        /// Загрузка стиля шрифта
        /// </summary>
        private void setFontStyle()
        {
            fStyle = FontStyle.Regular;
            switch (PLPg.tk((int)g_style.fontStyle))
            {
                case "Regular": fStyle = FontStyle.Regular; break;
                case "Bold": fStyle = FontStyle.Bold; break;
                case "Italic": fStyle = FontStyle.Italic; break;
                case "Bold, Italic": fStyle = FontStyle.Bold | FontStyle.Italic; break;
                case "Underline": fStyle = FontStyle.Underline; break;
                case "Strikeout": fStyle = FontStyle.Strikeout; break;
            }
        }

        /// <summary>
        /// Получаем количество загруженных строк
        /// </summary>
        private void getCount()
        {
            toolStripStatusLabel2.Text = string.Concat("RowCount = ",(dataGridView1.RowCount - 1).ToString());
        }

        /// <summary>
        /// Форма SQL запроса
        /// </summary>
        private void querySQL()
        {
            //Инициализация формы
            qSQL = new Form();
            qSQL.Width = 610;
            qSQL.Height = 400;
            qSQL.StartPosition = FormStartPosition.CenterParent;
            qSQL.FormBorderStyle = FormBorderStyle.FixedToolWindow;

            // Создание ЛистБокса
            qSQL_LB = new ListBox();
            qSQL_LB.Font = new Font("Arial", 12);
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_1));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_2));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_3));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_4));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_5));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_6));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_7));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_8));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_9));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_10));
            qSQL_LB.Width = 600;
            qSQL_LB.Height = 200;
            qSQL_LB.Click += new EventHandler(qSQL_LB_Click);
            qSQL_LB.DoubleClick += new EventHandler(qSQL_LB_DoubleClick);

            // Создание ТекстБокса
            qSQL_TB = new TextBox();
            qSQL_TB.Text = "";
            qSQL_TB.BorderStyle = BorderStyle.FixedSingle;
            qSQL_TB.Location = new Point(0,190);
            qSQL_TB.Width = 600;
            qSQL_TB.Height = 200;
            qSQL_TB.Multiline = true;
            qSQL_TB.Font = new Font("Arial", 14);
            qSQL_TB.KeyDown += new KeyEventHandler(qSQL_TB_KeyDown);

            qSQL.Text = "ВВЕДИТЕ SQL ЗАПРОС";
            qSQL.Controls.Add(qSQL_TB);
            qSQL.Controls.Add(qSQL_LB);
            qSQL.ShowDialog();
        }

        /// <summary>
        /// Форма выбора периода
        /// </summary>
        private void datePik()
        {
            // Инициализация формы
            Date = new Form();
            Date.Text = "Период";
            Date.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            Date.StartPosition = FormStartPosition.CenterParent;
            Date.Width = 355;
            Date.Height = 250;

            // Создание MonthCalendar 1
            MonthCalendar dtPik1 = new MonthCalendar();
            dtPik1.Font = new Font("Arial", 10);
            dtPik1.SelectionStart = Convert.ToDateTime(PLPg.tk((int)g_style.periodS));
            dtPik1.DateSelected += new DateRangeEventHandler(dtPik1_DateSelected);

            // Создание MonthCalendar 2
            MonthCalendar dtPik2 = new MonthCalendar();
            dtPik2.Font = new Font("Arial", 10);
            dtPik2.Location = new System.Drawing.Point(175,0);
            dtPik2.SelectionStart = Convert.ToDateTime(PLPg.tk((int)g_style.periodPo));
            dtPik2.DateSelected += new DateRangeEventHandler(dtPik2_DateSelected);

            // Создание кнопки ОК
            Button bOk = new Button();
            bOk.Text = "OK";
            bOk.Location = new Point(140, 190);
            bOk.Click += new EventHandler(bOk_Click);

            // Добавление элементов
            Date.Controls.Add(dtPik1);
            Date.Controls.Add(dtPik2);
            Date.Controls.Add(bOk);
            Date.ShowDialog();
        }

        /// <summary>
        /// Обновление ЛистБокса с полями
        /// </summary>
        private void updateListBox()
        {
            toolStripComboBox1.Items.Clear();
            int i = dataGridView1.Columns.Count;
            int i1 = 0;
            while (i1 < i)
            {
                toolStripComboBox1.Items.Add(dataGridView1.Columns[i1].HeaderText);
                i1++;
            }
            toolStripComboBox1.SelectedIndex = 0;
        }

        /// <summary>
        /// Заполнение списка автозавершения ТекстБокса
        /// </summary>
        private void setComplete()
        {
            toolStripTextBox1.AutoCompleteCustomSource.Clear();
            for (int i = 22; i <= 31; i++)
            {
                toolStripTextBox1.AutoCompleteCustomSource.Add(PLPg.tk(i));
            }
        }

        /// <summary>
        /// Вывод на печать через класс HK.Reports
        /// </summary>
        //private void printTable()
        //{
        //    DataTable printTab = (DataTable)this.dataGridView1.DataSource;
        //    Report r = new Report(
        //        "Report", 
        //        printTab, 
        //        PLPg.tk((int)g_style.headReport), 
        //        "ИТОГО:", 
        //        PLPg.tk((int)g_style.width), 
        //        PLPg.tk((int)g_style.captions));
        //    r.ShowReport();
        //}

        /// <summary>
        /// Отображение текущего сервера
        /// </summary>
        private void setCurServ()
        {
            toolStripComboBox2.Text = PLPg.tk((int)g_style.serv);
        }
        #endregion


    }
}

